package k8sutil

import (
	"fmt"
	"k8s.io/client-go/tools/clientcmd"
)

func GetClusterName() (string, error) {
	loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
	configOverrides := &clientcmd.ConfigOverrides{}
	clientConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, configOverrides)

	rawConfig, err := clientConfig.RawConfig()
	if err != nil {
		return "", fmt.Errorf("failed to load kubeconfig: %v", err)
	}

	// 默认 context 对应的 cluster 名称
	contextName := rawConfig.CurrentContext
	if contextName == "" {
		return "", fmt.Errorf("可能未找到kubeconfig！")
	}
	return contextName, nil
}

func GetClusterNameByKubeconfig(kubeconfig string) (string, error) {
	config, err := clientcmd.LoadFromFile(kubeconfig)
	if err != nil {
		return "", fmt.Errorf("load kubeconfig failed: %v", err)
	}

	// 获取当前 context
	currentContext := config.CurrentContext
	if currentContext == "" {
		return "", fmt.Errorf("no current context set in kubeconfig")
	}
	return currentContext, nil
}
